package com.itheima.aspect;

import com.itheima.aspect.annotation.MyLog;
import com.itheima.commen.BaseContext;
import com.itheima.commen.CustomException;
import com.itheima.commen.Result;
import com.itheima.entiry.Log;
import com.itheima.service.ReggieLogService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.TimerTask;

@Component
@Aspect
public class AnnotationAspect {
    @Autowired
    private ReggieLogService reggieLogService;



    @Pointcut("@annotation(com.itheima.aspect.annotation.MyLog)")
    private void Method(){}

    @Around("Method()")
    public Object LogHandler(ProceedingJoinPoint pjp){


        Log reggieLog = new Log();


        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Method method = signature.getMethod();

        MyLog annotation = method.getAnnotation(MyLog.class);
        String name = annotation.name();
        String value = annotation.value();

        reggieLog.setRecord(value);
        reggieLog.setUserId(BigDecimal.valueOf(BaseContext.getCurrentId()));
        reggieLog.setName(name);
//        reggieLog.setId(1);

        reggieLog.setTime(LocalDateTime.now());

        Object proceed = null;
        try {
            System.out.println("");
            proceed = pjp.proceed();


        } catch (Throwable throwable) {
            new AsyncManager().execute(new TimerTask() {
                @Override
                public void run() {
                    reggieLogService.save(reggieLog);
                }
            });

            throw new CustomException("aop");
        }finally {
           new AsyncManager().execute(new TimerTask() {
               @Override
               public void run() {
                   reggieLogService.save(reggieLog);
               }
           });

//            System.out.println(reggieLog.getId());
        }
        return proceed;
    }
}
